import requests
from lxml import etree
import time

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
    "content-type": "application/x-www-form-urlencoded",
}
url = "https://music.163.com/discover/playlist/"

for page in range(0, 19):
    params = {
        "order": "hot",  # 按照热度排序
        "cat": "全部",    # category
        "limit": "35",
        "offset": f"{page * 35}"
    }

    response = requests.get(url, params=params, headers=headers)
    # 从服务器获取的原始响应数据转换为可读的文本格式
    html_str = response.content.decode()
    # 把 HTML 字符串解析成树形结构，以便进行后续的处理
    root = etree.HTML(html_str)
    music_list = root.xpath("//div[@class='g-wrap p-pl f-pr']/ul/li")

    print(f"**********第{page + 1}页开始**********")
    for music in music_list:
        music_title = "".join(music.xpath(".//p[@class='dec']/a/text()"))
        music_url = "https://music.163.com/#" + "".join(music.xpath(".//p[@class='dec']/a/@href"))
        music_author = "".join(music.xpath(".//a[@class='nm nm-icn f-thide s-fc3']/text()"))
        music_plays = "".join(music.xpath(".//div[@class='bottom']/span[@class='nb']/text()"))
        print(f"歌单名:{music_title}\n作者:{music_author}\n播放量:{music_plays}\n封面链接:{music_url}")

    print(f"__________第{page + 1}页结束__________")
    print(f"共{params["offset"]}条数据")
    time.sleep(2)


